package tliasweb.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pojo.UserLoginDTO;
import tliasweb.Constants;
import tliasweb.entity.Emp;
import tliasweb.mapper.EmpMapper;
import tliasweb.service.UserService;
import util.JwtUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private EmpMapper empMapper;

    @Override
    public String login(UserLoginDTO dto) {
        // 根据用户名查用户
        Emp emp = empMapper.selectByUsername(dto.getUsername());
        // 查不到就失败
        if(emp == null){
            log.error("用户名不存在，username:{}", dto.getUsername());
            return null;
        }
        // 比对密码是否匹配
        String passwordDB = emp.getPassword();
        String passwordInput = dto.getPassword();
        // 不匹配 失败
        if(!Objects.equals(passwordDB, passwordInput)){
            log.error("密码错误，username:{}, password:{}", dto.getUsername(), dto.getPassword());
            return null;
        }
        // 匹配 成功， 生成jwt token
        Map<String, Object> data = new HashMap<>();
        data.put(Constants.ID, emp.getId());
        data.put(Constants.USERNAME, emp.getUsername());
        String token = JwtUtils.generateJwt(data);
        return token;
    }
}
